﻿using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;

namespace Framework.Core.Recorder
{
    internal class DependencyRepository : IDependencyRepository
    {
        private readonly IDictionary<string, DependencyCall> repository;

        private readonly ISerializer serializer;
        private readonly object syncRoot = new object();

        public DependencyRepository(ISerializer serializer)
        {
            this.serializer = serializer;
            repository = new Dictionary<string, DependencyCall>();
        }

        public DependencyRepository(ISerializer serializer, Stream stream)
            : this(serializer)
        {
            repository = (IDictionary<string, DependencyCall>)serializer.Deserialize(stream);
        }

        public DependencyCall TryGet(string recordKey, out bool succeed)
        {
            lock (syncRoot)
            {
                succeed = false;
                if (!repository.ContainsKey(recordKey))
                {
                    return null;
                }

                succeed = true;
                return repository[recordKey];
            }
        }

        public void Update(string recordKey, DependencyCall dependencyCall)
        {
            lock (syncRoot)
            {
                repository[recordKey] = dependencyCall;
            }
        }

        public void Serialize(Stream stream)
        {
            lock (syncRoot)
            {
                try
                {
                    serializer.Serialize(repository, stream);
                }
                catch (SerializationException e)
                {
                    throw new HardMockException(e.Message);
                }
            }
        }
    }
}